package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.News;
import cn.wolfcode.trip.base.domain.NewsContent;
import cn.wolfcode.trip.base.mapper.NewsCommendMapper;
import cn.wolfcode.trip.base.mapper.NewsContentMapper;
import cn.wolfcode.trip.base.mapper.NewsMapper;
import cn.wolfcode.trip.base.query.NewsQueryObject;
import cn.wolfcode.trip.base.service.INewsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NewsServiceImpl implements INewsService {
    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private NewsContentMapper contentMapper;
   @Autowired
private NewsCommendMapper commendMapper;

    @Override
    public PageInfo<News> query(NewsQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<News> list = newsMapper.queryForList(qo);
        return new PageInfo<>(list);


    }

    @Override
    public News getNews(Long newsId) {
        News news = newsMapper.selectByPrimaryKey(newsId);
        NewsContent newsContent = contentMapper.selectByPrimaryKey(news.getId());
        news.setNewsContent(newsContent);

        return news;
    }

    @Override
    public PageInfo<News> getReferenceNews(NewsQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<News> list = newsMapper.getReferenceNews(qo);
        return new PageInfo<>(list);
    }

    @Override
    public void updateState(News news) {

        newsMapper.updateState(news);
        commendMapper.deleteByPrimaryKey(news.id);
    }

    @Override
    public NewsContent getNewsContentById(Long id) {

         return contentMapper.selectByPrimaryKey(id);
    }

    @Override
    public void saveOrUpdate(News news) {
        NewsContent Content = news.getNewsContent();
        if (news.getId()==null) {

            news.setReleaseTime(new Date());
            newsMapper.insert(news);
            Content.setId(news.getId());
            contentMapper.insert(Content);
        }else {
            newsMapper.updateByPrimaryKey(news);
            Content.setId(news.getId());
            contentMapper.updateByPrimaryKey(Content);
        }
    }
}
